package com.sds.sweng.swat.miplatform.ui.design.parts.area.sub;

import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.eclipse.draw2d.FlowLayout;
import org.eclipse.draw2d.IFigure;
import org.eclipse.draw2d.PositionConstants;
import org.eclipse.gef.EditPolicy;

import com.sds.sweng.swat.miplatform.ui.design.figures.geps.GepsTitleSubAreaFigure;
import com.sds.sweng.swat.miplatform.ui.design.layouts.FlowLayoutEx;
import com.sds.sweng.swat.miplatform.ui.design.models.area.sub.SubArea;
import com.sds.sweng.swat.miplatform.ui.design.models.area.sub.TitleSubArea;
import com.sds.sweng.swat.miplatform.ui.design.models.component.MButton;
import com.sds.sweng.swat.miplatform.ui.design.policies.NonCreateFlowLayoutEditPolicy;

public class TitleSubAreaPart extends SubAreaPart {

	protected IFigure createFigure() {
		GepsTitleSubAreaFigure f = new GepsTitleSubAreaFigure(((SubArea) getModel()).getName());
		f.setLabelAlignment(PositionConstants.CENTER);

		int subAreaWidth = getAreaWidth();
		f.setSize(subAreaWidth, SubArea.MODEL_HEIGHT);

		((SubArea) getModel()).setWidth(getContentsWidth());

		drawChildren(f);

		return f;
	}

	private void drawChildren(GepsTitleSubAreaFigure parent) {
		FlowLayoutEx layout = new FlowLayoutEx();
		layout.setMajorAlignment(FlowLayout.ALIGN_RIGHTBOTTOM);
		layout.setMinorSpacing(3);
		parent.setLayoutManager(layout);

		TitleSubArea area = (TitleSubArea) getModel();
		String title = area.getTitle();
		List<MButton> buttons = area.getButtons();

		if (buttons.size() > 0 || !StringUtils.isEmpty(title)) {
			parent.setTitle(title);
			parent.setText(StringUtils.EMPTY);
			parent.setLabelAlignment(PositionConstants.LEFT);
		} else {
			parent.setTitle(StringUtils.EMPTY);
			parent.setText(area.getName());
			parent.setLabelAlignment(PositionConstants.CENTER);
		}

		parent.repaint();
	}

	protected void createEditPolicies() {
		super.createEditPolicies();

		installEditPolicy(EditPolicy.LAYOUT_ROLE, new NonCreateFlowLayoutEditPolicy());
	}

	protected void refreshVisuals() {
		drawChildren((GepsTitleSubAreaFigure) getFigure());
	}

}
